/*
 * @Author: fhw
 * @Date: 2022-07-01 15:39:20
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-03-29 13:40:23
 * @Description:
 */
import { defineComponent, PropType, ref } from 'vue'
import { CloudUploadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { isNil } from 'ramda'
import { errorTips } from '@/utils'
import { WatermarkDataState } from '@/utils/watermark'
import { AilOSS, OssData } from '@/utils/upload'
export interface FileInfo {
	file: Blob
	fileList: FileItem[]
}

interface FileItem {
	uid: string
	name?: string
	status?: string
	response?: string
	url?: string
	type?: string
	size: number
	originFileObj: any
}
const props = {
	accept: {
		type: String as PropType<string>,
		default: '.jpg,.png,.jpeg',
	},
	src: {
		type: String as PropType<string>,
		default: '',
	},
	style: {
		type: [String, Object] as PropType<string | object | any>,
		default: '',
	},
	watermarkData: {
		type: Object as PropType<WatermarkDataState>,
		default: {}
	},
	isWatermark: {
		type: Boolean as PropType<boolean>,
		default: false
	}
} as const
export default defineComponent({
	emits: ['change', 'update:src'],
	props,
	setup(props, { emit, slots }) {
		const loading = ref(false)
		async function handleChange(info: FileInfo) {
			const reg = props.accept.split(',').map(ext => ext.trim().replace(/\.[^.]+$/, match => match.replace('.', ''))).join('|')
			if (!new RegExp(`\\.(${reg})$`, 'i').test((info.file as any).name.toLowerCase())) {
				message.error(`上传格式不正确，请上传${props.accept}格式`)
				return false
			}
			loading.value = true
			const curFiles = info.file as File
			try {
				const data = await AilOSS.uploadOSS(curFiles)
				console.log(data, '=========');

				loading.value = false
				// 如果想进行更多操作或者显示到页面上，可以根据需求修改下面的代码
				emit('change', {
					...data,
					name: curFiles.name,
					byte: (curFiles.size / (1024 * 1024)).toFixed(4),
				} as OssData)
				if (data.url) {
					emit('update:src', data.url)
				}
			} catch (error) {
				loading.value = false
				errorTips('上传文件失败:' + error)
			}

		}
		return () => (
			<a-spin spinning={loading.value} tip="上传中...">
				<a-upload
					name="avatar"
					list-type="picture-card"
					class="avatar-uploader"
					show-upload-list={false}
					before-upload={() => false}
					onChange={handleChange}
					accept={props.accept}

				>
					{slots['text'] ? (
						slots['text']?.()
					) : props.src ? (
						<div style={props.style} class="flexBox">
							<a-image src={props.src} alt="" style="width: 100%" />
						</div>
					) : (
						<p class="ant-upload-drag-icon flexBox" style={props.style}>
							<CloudUploadOutlined style="font-size: 40px;color:#40a9ff" />
						</p>
					)}
				</a-upload>
			</a-spin>
		)
	},
})
